package com.yuerlive.rainbow.module.main;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.mrd.mina.MinaHelper;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.uinfo.constant.UserInfoFieldEnum;
import com.yuerlive.rainbow.R;
import com.umeng.socialize.UMShareAPI;
import com.yuerlive.rainbow.base.BaseActivity;
import com.yuerlive.rainbow.common.ActivityStack;
import com.yuerlive.rainbow.common.AppConfig;
import com.yuerlive.rainbow.controller.LiveRoomController;
import com.yuerlive.rainbow.entity.PushExtra;
import com.yuerlive.rainbow.entity.SignData;
import com.yuerlive.rainbow.entity.SignInfo;
import com.yuerlive.rainbow.entity.User;
import com.yuerlive.rainbow.entity.UserInfo;
import com.yuerlive.rainbow.entity.VersionInfo;
import com.yuerlive.rainbow.module.live.LiveRoomActivity;
import com.yuerlive.rainbow.module.main.fragment.FragmentLive;
import com.yuerlive.rainbow.module.main.fragment.FragmentMain;
import com.yuerlive.rainbow.module.main.fragment.FragmentMine;
import com.yuerlive.rainbow.module.main.mainInterface.MainFragmentListener;
import com.yuerlive.rainbow.module.main.presenter.MainContract;
import com.yuerlive.rainbow.module.main.presenter.MainPresenter;
import com.yuerlive.rainbow.module.playlive.PlayLiveRoomActivity;
import com.yuerlive.rainbow.module.web.WebViewActivity;
import com.yuerlive.rainbow.nim.NimHelper;

import com.yuerlive.rainbow.service.DownloadService;
import com.yuerlive.rainbow.service.JPushUtil;
import com.yuerlive.rainbow.utils.DeviceUtils;
import com.yuerlive.rainbow.utils.L;
import com.yuerlive.rainbow.utils.LeakUtil;
import com.yuerlive.rainbow.utils.PreferenceUtils;
import com.yuerlive.rainbow.utils.UserProxy;
import com.yuerlive.rainbow.widget.CustomDialog;
import com.yuerlive.rainbow.widget.FlowLayout;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements MainFragmentListener, MainContract.View {
    @BindView(R.id.imgBarHome)
    ImageView imgBarHome;
    @BindView(R.id.imgBarStarted)
    ImageView imgBarStarted;
    @BindView(R.id.imgBarMine)
    ImageView imgBarMine;
    @BindView(R.id.rlParent)
    RelativeLayout rlParent;


    private ObjectAnimator mHideAnim; // 隐藏的动画
    private ObjectAnimator mShowAnim; // 显现的动画
    private boolean mIsHidden; // 是否已隐藏
    private float mPxHeight; // BottomNavigationView 的 px 高度

    private Class[] classes = {FragmentMain.class, FragmentLive.class, FragmentMine.class};
    private List<Fragment> fragments;

    private MainContract.Presenter presenter;
    private CustomDialog updateDialog;
    private CustomDialog signInDialog;
    private List<SignData> signDatas = new ArrayList();
    private int signGetMoney;
    CustomDialog signDialog;
    TextView tvCount;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initViews() {
        L.e(TAG, "initViews");
        //网络请求的时候getDevicedId() 要READ_PHONE_STATE权限 所以进入页面就请求此权限
        if (!checkPermissions(new String[]{Manifest.permission.READ_PHONE_STATE})) {
            requestPermission(new String[]{Manifest.permission.READ_PHONE_STATE}, 0x0003);
            return;
        }
        presenter = new MainPresenter(this);
        presenter.checkVersion();
        initMinaConnect();
        initNim();
        fragments = new ArrayList<>();
        for (int i = 0; i < classes.length; i++) {
            fragments.add(null);
        }
        setSelectItem(0);
        initAnimation();
        JPushUtil jpushUtil = JPushUtil.getInstance();
        String userId = UserProxy.getUser().getUserId();
        if (!TextUtils.isEmpty(userId)) {
//            jpushUtil.setAliasWithTags(mContext.getResources().getString(R.string.alias) + user.getId(), JPushUtil.initTags(user));
            if (AppConfig.isTest()) {
                jpushUtil.setAliasWithTags(getResources().getString(R.string.alias_test) + userId, JPushUtil.initTags());
            } else {
                jpushUtil.setAliasWithTags(getResources().getString(R.string.alias) + userId, JPushUtil.initTags());
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        L.e(TAG, "onResume");
        if (UserProxy.getUser() == null) return;
        long current = System.currentTimeMillis();
        String userId = UserProxy.getUser().getUserId();
        if (PreferenceUtils.getLong(userId + "_SIGN_TIME") <= 0) {
            PreferenceUtils.putLong(userId + "_SIGN_TIME", current);
            presenter.getSignData();
        } else {
            Date date = new Date(PreferenceUtils.getLong(UserProxy.getUser().getUserId() + "_SIGN_TIME"));
            Date currentDate = new Date(current);
            if (date.getDate() == currentDate.getDate() && date.getMonth() == currentDate.getMonth()) { //同一天
                if (!PreferenceUtils.getBoolean(UserProxy.getUser().getUserId() + "_SIGN_SUCCESS")) {
                    presenter.getSignData();
                }
            } else {
                PreferenceUtils.putBoolean(UserProxy.getUser().getUserId() + "_SIGN_SUCCESS", false);
                PreferenceUtils.putLong(userId + "_SIGN_TIME", current);  //新的一天
                presenter.getSignData();
            }
        }
    }

    /*初始化签到奖励对话框*/
    private void initSignDialog() {
        if (signDialog == null) {
            View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_sign, null);
            signDialog = new CustomDialog(mActivity, view);
            view.findViewById(R.id.ivCancel).setOnClickListener(
                    (v) -> signDialog.dismiss()
            );
            tvCount = (TextView) view.findViewById(R.id.tvCount);
        }
        if (!signDialog.isShowing()) {
            signDialog.show();
        }
    }

    private void initSignInDialog() {
        if (signInDialog == null) {
            View v = LayoutInflater.from(mActivity).inflate(R.layout.layout_signin, null);
            signInDialog = new CustomDialog(mActivity, v, 0);
            FlowLayout llContainer = (FlowLayout) v.findViewById(R.id.llContainer);
            int giftWidth = (((int) (DeviceUtils.deviceWidth(mActivity) * 0.9)) - DeviceUtils.dp2px(mActivity, 22) * 2 - DeviceUtils.dp2px(mActivity, 18) * 2) / 3;
            //只添加前六天的布局
            for (int i = 0; i < signDatas.size() - 1; i++) {
                ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(giftWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
                if (i % 3 == 1) {
                    params.setMargins(DeviceUtils.dp2px(mActivity, 18), 0, DeviceUtils.dp2px(mActivity, 18), 0);
                } else {
                    params.setMargins(0, 0, 0, 0);
                }
                llContainer.addView(createSignItem(signDatas.get(i), i, llContainer), params);
                L.e("FlowLayout", "_______________________");
            }
            TextView tvSignBtn = (TextView) v.findViewById(R.id.tvSignBtn);
            tvSignBtn.setOnClickListener((view) -> {
                presenter.signRequest();
                signInDialog.dismiss();
            });
        }
    }

    private View createSignItem(SignData signData, int i, FlowLayout llContainer) {
        final View view = LayoutInflater.from(mActivity).inflate(R.layout.layout_sign_item, llContainer, false);
        TextView tvMoney = (TextView) view.findViewById(R.id.tvMoney);
        ImageView ivCanGet = (ImageView) view.findViewById(R.id.ivCanGet);
        ImageView ivHasGet = (ImageView) view.findViewById(R.id.ivHasGet);
        RelativeLayout rlMask=(RelativeLayout)view.findViewById(R.id.rlMask);
        TextView tvDay = (TextView) view.findViewById(R.id.tvDay);
        tvMoney.setText("x" + signData.getPrizeMoney());
        if (signData.getIsGetSign() == 1) {
            ivCanGet.setVisibility(View.GONE);
            ivHasGet.setVisibility(View.VISIBLE);
            rlMask.setVisibility(View.VISIBLE);
        } else if(signData.getIsGetSign()==2){
            ivCanGet.setVisibility(View.VISIBLE);
            ivHasGet.setVisibility(View.GONE);
            rlMask.setVisibility(View.GONE);
        }else if(signData.getIsGetSign()==3){
            ivCanGet.setVisibility(View.GONE);
            ivHasGet.setVisibility(View.GONE);
            rlMask.setVisibility(View.GONE);
        }
        tvDay.setText(signData.getDay());
        return view;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        L.e(TAG, "onNewIntent");
        if (intent.hasExtra("category")) {
            distriBution(intent);
        } else {
            initNim();
        }
    }

    /**
     * 从通知栏打开应用
     *
     * @param intent
     */
    private void distriBution(Intent intent) {
        String target = intent.getStringExtra("category");
        if (target == null) return;
        Intent newIntent = new Intent();
        switch (target) {
            case PushExtra.KEY_LIVE://直播
                newIntent.setClass(this, LiveRoomActivity.class);
//                newIntent.putExtra("id", intent.getStringExtra("id"));
                PushExtra.LiveData liveData = new Gson().fromJson(intent.getStringExtra("liveData"), PushExtra.LiveData.class);
                newIntent.putExtra("liveId", liveData.getLive_id());
                newIntent.putExtra("chatroomId", liveData.getChat_room_id());
                newIntent.putExtra("liveCover", liveData.getLive_icon());
                LiveRoomController.getInstance().enterLiveRoom(this,newIntent);
                break;
            case PushExtra.KEY_VIDEO://视频
                break;
            case PushExtra.KEY_URL: //外部页面
                newIntent.setClass(this, WebViewActivity.class);
                newIntent.putExtra("url", intent.getStringExtra("url"));
                startActivity(newIntent);
                break;
            case PushExtra.KEY_NONE:
                //do nothing
                break;
        }
    }

    private void initNim() {
        NimHelper.login(NimHelper.generateLoginInfo(UserProxy.getUser().getUserId(), UserProxy.getUser().getUserId()), new RequestCallback() {
            @Override
            public void onSuccess(Object param) {
                L.e(TAG, "onSuccess   " + param.toString());
                NimHelper.updateUserInfo(UserInfoFieldEnum.Name, UserProxy.getUser().getUserInfo().getNickname());
            }

            @Override
            public void onFailed(int code) {
                L.e(TAG, "onFailed   " + code);
            }

            @Override
            public void onException(Throwable exception) {
                L.e(TAG, "onException   " + exception);
            }
        });
    }

    private void initAnimation() {
        mIsHidden = false;
        mPxHeight = DeviceUtils.dp2px(this, 50);
        mHideAnim = ObjectAnimator.ofFloat(rlParent, "translationY", 0, mPxHeight)
                .setDuration(300);
        mShowAnim = ObjectAnimator.ofFloat(rlParent, "translationY", mPxHeight, 0)
                .setDuration(300);
    }

    public void hide() {
        mIsHidden = true;
        mHideAnim.start();
    }

    public void show() {
        mIsHidden = false;
        mShowAnim.start();
    }

    public boolean isHidden() {
        return mIsHidden;
    }

    public void setSelectItem(int position) {

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        //先隐藏所有fragment
        for (Fragment fragment : fragments) {
            if (null != fragment) {
                fragmentTransaction.hide(fragment);
            }
        }
        Fragment fragment;
        if (null == fragments.get(position)) {
            Bundle bundle = new Bundle();
            // bundle.putString(Constant.TITLE, drawerTitles[position]);
            fragment = Fragment.instantiate(this, classes[position].getName(), bundle);

            // 如果Fragment为空，则创建一个并添加到界面上
            fragmentTransaction.add(R.id.fragment_content, fragment);
            fragments.set(position, fragment);
        } else {
            // 如果Fragment不为空，则直接将它显示出来
            fragment = fragments.get(position);
            fragmentTransaction.show(fragment);
        }
        fragmentTransaction.commitAllowingStateLoss();

    }

    @OnClick({R.id.llBarHome, R.id.llBarMine, R.id.llBarStarted})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llBarHome:
                changeBarState(0);
                setSelectItem(0);
                break;
            case R.id.llBarMine:
                changeBarState(2);
                setSelectItem(2);
                ((FragmentMine) fragments.get(2)).getUserInfo();
                break;
            case R.id.llBarStarted:
                if (UserProxy.getUser().getUserInfo().getIsCanLive() == 0) {
                    showSnackbar(getRootView(this), "目前仅签约主播可以开启直播，签约请联系客服QQ群：624846111", 0);
                    return;
                }
                if (!checkPermissions(new String[]{Manifest.permission.CAMERA})) {
                    requestPermission(new String[]{Manifest.permission.CAMERA}, 0x0003);
                    return;
                } else {
                    jumpToActivity(PlayLiveRoomActivity.class);
                }
                break;
        }
    }

    private void changeBarState(int pos) {
        if (pos == 0) {
            imgBarHome.setImageResource(R.drawable.bar_home_selected);
            imgBarMine.setImageResource(R.drawable.bar_mine_unselected);
        } else {
            imgBarHome.setImageResource(R.drawable.bar_home_unselected);
            imgBarMine.setImageResource(R.drawable.bar_mine_selected);
        }
    }


    @Override
    public void hideTopBar() {

    }

    @Override
    public void showTopBar() {

    }

    @Override
    public void hideBottomBar() {
        /*L.e(TAG, "hideBottomBar");
        if (!isHidden()) {
            L.e(TAG, "hideBottomBar22222");
            hide();
            L.e(TAG, "hideBottomBar3333333");
        }*/
    }

    @Override
    public void showBottomBar() {
       /* L.e(TAG, "showBottomBar");
        if (isHidden()) {
            L.e(TAG, "showBottomBar2222222");
            show();
            L.e(TAG, "showBottomBar33333333");
        }*/
    }

    @Override
    public boolean isShown() {
        return !isHidden();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        minaThread.interrupt();
        minaThread = null;
        ActivityStack.removeAll();
        LeakUtil.fixInputMethodManagerLeak(this);
        if (signDialog != null) {
            signDialog.dismiss();
        }
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                showToast("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void setPresenter(MainContract.Presenter presenter) {
        super.presenter = presenter;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void checkVersionReult(VersionInfo versionInfo) {
        if (versionInfo != null) {
            if (versionInfo.getVersionCode() > DeviceUtils.getVersionCode(this)) {
                showUpdateDialog(versionInfo);
            }
        }
    }

    @Override
    public void showSignResult(SignInfo info) {
        if (info.getIsSign() == 0) {
            initSignData(info);
            initSignInDialog();
            if (!signInDialog.isShowing()) {
                signInDialog.show();
            }
        }
    }
    @Override
    public void signRequstResult(int code) {
        if (code == 0) {
            User user = UserProxy.getUser();
            UserInfo info = user.getUserInfo();
            info.setRainbowSweet(info.getRainbowSweet() + signGetMoney);
            UserProxy.setUser(user);
            initSignDialog();
            tvCount.setText("x" + signGetMoney);
            PreferenceUtils.putBoolean(UserProxy.getUser().getUserId() + "_SIGN_SUCCESS", true);
        } else {
            showSnackbar(getRootView(mActivity), "签到失败", 0);
        }
    }

    private void initSignData(SignInfo info) {
        signDatas.clear();
        for (int i = 0; i < info.getRewardList().size(); i++) {
            SignData data = new SignData();
            switch (i) {
                case 0:
                    data.setDay("第一天");
                    break;
                case 1:
                    data.setDay("第二天");
                    break;
                case 2:
                    data.setDay("第三天");
                    break;
                case 3:
                    data.setDay("第四天");
                    break;
                case 4:
                    data.setDay("第五天");
                    break;
                case 5:
                    data.setDay("第六天");
                    break;
                case 6:
                    data.setDay("第七天");
                    break;
            }
            if(info.getSignTiems()>i){
                data.setIsGetSign(1);
            }else if(info.getSignTiems()==i){
                data.setIsGetSign(2);
            }else if(info.getSignTiems()<i){
                data.setIsGetSign(3);
            }
            data.setPrizeMoney(info.getRewardList().get(i));
            signDatas.add(data);
        }
        signGetMoney = info.getRewardList().get(info.getSignTiems());
    }

    private void showUpdateDialog(VersionInfo versionInfo) {
        if (updateDialog == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.layout_choose_dialog, null);
            TextView title = (TextView) view.findViewById(R.id.tvTitle);
            TextView tvContent = (TextView) view.findViewById(R.id.tvContent);
            TextView tvSure = (TextView) view.findViewById(R.id.btnSure);
            TextView tvCancel = (TextView) view.findViewById(R.id.btnCancel);
            updateDialog = new CustomDialog(this, view);
            title.setText("检测到新版本");
            tvContent.setText("系统检测到新版本:" + versionInfo.getVersion() + "，请更新至最新版本，获取更优质体验！");
            tvSure.setText("更新");
            tvCancel.setOnClickListener((v) -> updateDialog.dismiss());
            tvSure.setOnClickListener((v) -> {
                downloadApk(versionInfo);
                updateDialog.dismiss();
            });

            if (versionInfo.getIsCoercive() == 1) {
                tvCancel.setVisibility(View.GONE);
                updateDialog.setCancelable(false);
                updateDialog.setCanceledOnTouchOutside(false);
            } else {
                tvCancel.setVisibility(View.VISIBLE);
                updateDialog.setCancelable(true);
                updateDialog.setCanceledOnTouchOutside(true);
            }

        } else {
            updateDialog.show();
        }
    }

    /*下载更新*/
    private void downloadApk(VersionInfo version) {
        Intent it = new Intent(MainActivity.this, DownloadService.class);
        it.putExtra("apkUrl", version.getUrl());
        startService(it);

        ServiceConnection conn = new ServiceConnection() {
            @Override
            public void onServiceDisconnected(ComponentName name) {

            }

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {

            }
        };
        bindService(it, conn, BIND_AUTO_CREATE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

    }

    private Thread minaThread;

    private void initMinaConnect() {
        if (minaThread == null) {
            minaThread = new Thread(() -> {
                try {
                    MinaHelper.getInstance().connect(null, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
            minaThread.start();
        }
    }

    public void doBottomTranslationY(int tranxlationY) {
        ObjectAnimator animator;
        if (tranxlationY == 0) {
            animator = ObjectAnimator.ofFloat(rlParent, "translationY", rlParent.getTranslationY(), 0);
        } else {
            animator = ObjectAnimator.ofFloat(rlParent, "translationY", rlParent.getTranslationY(), rlParent.getHeight());
        }
        animator.setDuration(200);
        animator.start();
    }
}
